<template>
  <div class="department-management">
    <div class="page-header">
      <h1 class="page-title">科室管理</h1>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="showAddDialog = true">
          新增科室
        </el-button>
        <el-button :icon="View" @click="viewMode = viewMode === 'table' ? 'tree' : 'table'">
          {{ viewMode === 'table' ? '树形视图' : '列表视图' }}
        </el-button>
        <el-button :icon="Download" @click="exportData">
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #409EFF;">
              <el-icon><OfficeBuilding /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ departmentStats.total }}</div>
              <div class="stat-label">科室总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #67C23A;">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ departmentStats.capacity.totalDoctors }}</div>
              <div class="stat-label">医生总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #E6A23C;">
              <el-icon><House /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ departmentStats.capacity.totalBeds }}</div>
              <div class="stat-label">床位总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #F56C6C;">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ departmentStats.capacity.bedOccupancy }}%</div>
              <div class="stat-label">床位使用率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索科室名称、编码或主任"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterType" placeholder="科室类型" clearable @change="handleFilter">
            <el-option label="临床科室" value="临床科室" />
            <el-option label="医技科室" value="医技科室" />
            <el-option label="行政科室" value="行政科室" />
            <el-option label="后勤科室" value="后勤科室" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStatus" placeholder="运营状态" clearable @change="handleFilter">
            <el-option label="正常运营" value="正常运营" />
            <el-option label="暂停服务" value="暂停服务" />
            <el-option label="科室调整" value="科室调整" />
            <el-option label="筹建中" value="筹建中" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <div class="stats-info">
            <span class="stat-item">运营中: <strong>{{ departmentStats.active }}</strong></span>
            <span class="stat-item">满意度: <strong>{{ departmentStats.financial.averageSatisfaction }}</strong></span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 科室列表/树形视图 -->
    <el-card shadow="never">
      <!-- 表格视图 -->
      <el-table
        v-if="viewMode === 'table'"
        :data="paginatedDepartments"
        v-loading="loading"
        stripe
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="科室编码" width="100" />
        <el-table-column prop="name" label="科室名称" min-width="150">
          <template #default="{ row }">
            <el-button type="text" @click="handleViewDetail(row)">
              {{ row.name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)" size="small">
              {{ row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelColor(row.level)" size="small">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="director.name" label="科主任" width="100" />
        <el-table-column prop="location" label="位置" width="150">
          <template #default="{ row }">
            {{ row.location.building }} {{ row.location.floor }} {{ row.location.room }}
          </template>
        </el-table-column>
        <el-table-column prop="capacity.beds" label="床位数" width="80" />
        <el-table-column prop="capacity.doctors" label="医生数" width="80" />
        <el-table-column prop="capacity.currentPatients" label="在院患者" width="100" />
        <el-table-column prop="performance.satisfaction" label="满意度" width="80">
          <template #default="{ row }">
            <el-rate 
              v-model="row.performance.satisfaction" 
              disabled 
              show-score 
              text-color="#ff9900"
              :max="5"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleStaff(row)">
              人员
            </el-button>
            <el-dropdown @command="(command: string) => handleMoreActions(command, row)">
              <el-button type="text" size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="equipment">设备管理</el-dropdown-item>
                  <el-dropdown-item command="budget">预算管理</el-dropdown-item>
                  <el-dropdown-item command="performance">绩效统计</el-dropdown-item>
                  <el-dropdown-item command="disable" :disabled="row.capacity.currentPatients > 0">
                    {{ row.status === '正常运营' ? '暂停服务' : '恢复服务' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" :disabled="row.capacity.currentPatients > 0">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 树形视图 -->
      <el-tree
        v-else
        :data="departmentTree"
        node-key="id"
        :props="{ children: 'children', label: 'name' }"
        :expand-on-click-node="false"
        default-expand-all
        class="department-tree"
      >
        <template #default="{ node, data }">
          <div class="tree-node">
            <div class="node-info">
              <span class="node-name">{{ data.name }}</span>
              <el-tag :type="getTypeColor(data.type)" size="small">{{ data.type }}</el-tag>
              <span class="node-stats">
                床位: {{ data.capacity.beds }} | 医生: {{ data.capacity.doctors }}
              </span>
            </div>
            <div class="node-actions">
              <el-button type="text" size="small" @click="handleViewDetail(data)">详情</el-button>
              <el-button type="text" size="small" @click="handleEdit(data)">编辑</el-button>
            </div>
          </div>
        </template>
      </el-tree>

      <!-- 分页 (仅表格视图) -->
      <div v-if="viewMode === 'table'" class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredDepartments.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑科室对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingDepartment ? '编辑科室' : '新增科室'"
      width="800px"
      @close="resetForm"
    >
      <div class="form-content">
        <el-form
          ref="formRef"
          :model="departmentForm"
          :rules="formRules"
          label-width="100px"
        >
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="basic">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="科室名称" prop="name">
                    <el-input v-model="departmentForm.name" placeholder="请输入科室名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="科室编码" prop="code">
                    <el-input v-model="departmentForm.code" placeholder="请输入科室编码" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="科室类型" prop="type">
                    <el-select v-model="departmentForm.type" placeholder="请选择科室类型">
                      <el-option label="临床科室" value="临床科室" />
                      <el-option label="医技科室" value="医技科室" />
                      <el-option label="行政科室" value="行政科室" />
                      <el-option label="后勤科室" value="后勤科室" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="科室级别" prop="level">
                    <el-select v-model="departmentForm.level" placeholder="请选择科室级别">
                      <el-option label="一级科室" value="一级科室" />
                      <el-option label="二级科室" value="二级科室" />
                      <el-option label="三级科室" value="三级科室" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20" v-if="departmentForm.level !== '一级科室'">
                <el-col :span="12">
                  <el-form-item label="上级科室" prop="parentId">
                    <el-select v-model="departmentForm.parentId" placeholder="请选择上级科室">
                      <el-option 
                        v-for="dept in parentDepartments" 
                        :key="dept.id"
                        :label="dept.name"
                        :value="dept.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="科室描述">
                <el-input 
                  v-model="departmentForm.description" 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入科室描述"
                />
              </el-form-item>
            </el-tab-pane>

            <el-tab-pane label="位置信息" name="location">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="所在楼栋" prop="location.building">
                    <el-input v-model="departmentForm.location.building" placeholder="如：门诊楼" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="楼层" prop="location.floor">
                    <el-input v-model="departmentForm.location.floor" placeholder="如：3楼" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="房间号" prop="location.room">
                    <el-input v-model="departmentForm.location.room" placeholder="如：301-320" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系电话" prop="contact.phone">
                    <el-input v-model="departmentForm.contact.phone" placeholder="请输入联系电话" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="位置描述">
                <el-input 
                  v-model="departmentForm.location.description" 
                  placeholder="详细位置描述"
                />
              </el-form-item>
            </el-tab-pane>

            <el-tab-pane label="容量配置" name="capacity">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="床位数">
                    <el-input-number 
                      v-model="departmentForm.capacity.beds" 
                      :min="0" 
                      placeholder="床位数"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="医生数">
                    <el-input-number 
                      v-model="departmentForm.capacity.doctors" 
                      :min="0" 
                      placeholder="医生数"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="护士数">
                    <el-input-number 
                      v-model="departmentForm.capacity.nurses" 
                      :min="0" 
                      placeholder="护士数"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="当前患者">
                    <el-input-number 
                      v-model="departmentForm.capacity.currentPatients" 
                      :min="0" 
                      placeholder="当前患者数"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="loading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 科室详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="科室详情"
      width="1000px"
    >
      <div v-if="currentDepartment" class="department-detail">
        <el-tabs v-model="detailTab">
          <el-tab-pane label="基本信息" name="info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="科室名称">{{ currentDepartment.name }}</el-descriptions-item>
              <el-descriptions-item label="科室编码">{{ currentDepartment.code }}</el-descriptions-item>
              <el-descriptions-item label="科室类型">{{ currentDepartment.type }}</el-descriptions-item>
              <el-descriptions-item label="科室级别">{{ currentDepartment.level }}</el-descriptions-item>
              <el-descriptions-item label="上级科室">{{ currentDepartment.parentName || '无' }}</el-descriptions-item>
              <el-descriptions-item label="科主任">{{ currentDepartment.director.name }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ currentDepartment.contact.phone }}</el-descriptions-item>
              <el-descriptions-item label="科室邮箱">{{ currentDepartment.contact.email }}</el-descriptions-item>
              <el-descriptions-item label="位置">
                {{ currentDepartment.location.building }} {{ currentDepartment.location.floor }} {{ currentDepartment.location.room }}
              </el-descriptions-item>
              <el-descriptions-item label="成立时间">{{ currentDepartment.foundedDate }}</el-descriptions-item>
              <el-descriptions-item label="服务项目" :span="2">
                <el-tag v-for="service in currentDepartment.services" :key="service" class="service-tag">
                  {{ service }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="科室描述" :span="2">{{ currentDepartment.description }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <el-tab-pane label="容量统计" name="capacity">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card class="capacity-card">
                  <h4>床位情况</h4>
                  <div class="capacity-info">
                    <div class="capacity-item">
                      <span>总床位数：</span>
                      <strong>{{ currentDepartment.capacity.beds }}</strong>
                    </div>
                    <div class="capacity-item">
                      <span>当前患者：</span>
                      <strong>{{ currentDepartment.capacity.currentPatients }}</strong>
                    </div>
                    <div class="capacity-item">
                      <span>使用率：</span>
                      <strong>{{ ((currentDepartment.capacity.currentPatients / currentDepartment.capacity.beds) * 100).toFixed(1) }}%</strong>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card class="capacity-card">
                  <h4>人员配置</h4>
                  <div class="capacity-info">
                    <div class="capacity-item">
                      <span>医生数量：</span>
                      <strong>{{ currentDepartment.capacity.doctors }}</strong>
                    </div>
                    <div class="capacity-item">
                      <span>护士数量：</span>
                      <strong>{{ currentDepartment.capacity.nurses }}</strong>
                    </div>
                    <div class="capacity-item">
                      <span>床护比：</span>
                      <strong>1:{{ (currentDepartment.capacity.nurses / currentDepartment.capacity.beds).toFixed(1) }}</strong>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="绩效数据" name="performance">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-statistic title="月门诊量" :value="currentDepartment.performance.monthlyVisits" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="收入(万元)" :value="(currentDepartment.performance.revenue / 10000).toFixed(1)" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="成本(万元)" :value="(currentDepartment.performance.costs / 10000).toFixed(1)" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="利润(万元)" :value="(currentDepartment.performance.profit / 10000).toFixed(1)" />
              </el-col>
            </el-row>
            <el-divider />
            <div class="satisfaction-section">
              <h4>患者满意度</h4>
              <el-rate 
                v-model="currentDepartment.performance.satisfaction" 
                disabled 
                show-score 
                text-color="#ff9900"
                :max="5"
                size="large"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="设备清单" name="equipment">
            <el-table :data="currentDepartment.equipment" border>
              <el-table-column prop="name" label="设备名称" />
              <el-table-column prop="model" label="型号" />
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag :type="getEquipmentStatusColor(row.status)">
                    {{ row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="purchaseDate" label="采购日期" />
              <el-table-column prop="warrantyDate" label="保修到期" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 人员管理对话框 -->
    <el-dialog
      v-model="showStaffDialog"
      title="人员管理"
      width="800px"
    >
      <div class="staff-management">
        <el-empty description="人员管理功能开发中" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Download, Search, ArrowDown, View, OfficeBuilding, 
  User, House, TrendCharts
} from '@element-plus/icons-vue'
import { useDepartmentStore, type Department } from '@/stores/modules/department'

const departmentStore = useDepartmentStore()

// 响应式数据
const searchQuery = ref('')
const filterType = ref('')
const filterStatus = ref('')
const viewMode = ref<'table' | 'tree'>('table')
const currentPage = ref(1)
const pageSize = ref(20)
const activeTab = ref('basic')
const detailTab = ref('info')

// 对话框状态
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const showStaffDialog = ref(false)

const editingDepartment = ref<Department | null>(null)
const selectedDepartments = ref<Department[]>([])
const loading = ref(false)

// 表单相关
const formRef = ref()
const departmentForm = ref({
  name: '',
  code: '',
  type: '' as Department['type'],
  level: '' as Department['level'],
  parentId: '',
  parentName: '',
  director: {
    id: '',
    name: '',
    title: '',
    phone: '',
    email: ''
  },
  viceDirectors: [],
  location: {
    building: '',
    floor: '',
    room: '',
    description: ''
  },
  contact: {
    phone: '',
    extension: '',
    email: '',
    fax: ''
  },
  capacity: {
    beds: 0,
    doctors: 0,
    nurses: 0,
    currentPatients: 0
  },
  services: [] as string[],
  equipment: [],
  workingHours: {
    weekdays: {
      start: '08:00',
      end: '17:30'
    },
    weekends: {
      start: '08:00',
      end: '12:00'
    },
    holidays: false
  },
  budget: {
    annual: 0,
    used: 0,
    remaining: 0,
    categories: []
  },
  performance: {
    monthlyVisits: 0,
    satisfaction: 5,
    revenue: 0,
    costs: 0,
    profit: 0
  },
  status: '正常运营' as Department['status'],
  description: '',
  foundedDate: new Date().toISOString().split('T')[0]
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入科室编码', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择科室类型', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择科室级别', trigger: 'change' }
  ]
}

// 计算属性
const filteredDepartments = computed(() => {
  let result = departmentStore.departments
  
  if (searchQuery.value) {
    result = departmentStore.searchDepartments(searchQuery.value)
  }
  
  if (filterType.value) {
    result = result.filter(d => d.type === filterType.value)
  }
  
  if (filterStatus.value) {
    result = result.filter(d => d.status === filterStatus.value)
  }
  
  return result
})

const paginatedDepartments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredDepartments.value.slice(start, end)
})

const currentDepartment = computed(() => departmentStore.currentDepartment)
const departmentStats = computed(() => departmentStore.getDepartmentStats())
const departmentTree = computed(() => departmentStore.getDepartmentTree())

const parentDepartments = computed(() => {
  return departmentStore.departments.filter(d => d.level === '一级科室')
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleSelectionChange = (selection: Department[]) => {
  selectedDepartments.value = selection
}

const handleRowClick = (row: Department) => {
  departmentStore.currentDepartment = row
}

const handleViewDetail = (department: Department) => {
  departmentStore.currentDepartment = department
  showDetailDialog.value = true
}

const handleEdit = (department: Department) => {
  editingDepartment.value = department
  Object.assign(departmentForm.value, department)
  showAddDialog.value = true
}

const handleStaff = (department: Department) => {
  departmentStore.currentDepartment = department
  showStaffDialog.value = true
}

const handleMoreActions = async (command: string, department: Department) => {
  if (command === 'equipment') {
    ElMessage.info('设备管理功能开发中')
  } else if (command === 'budget') {
    ElMessage.info('预算管理功能开发中')
  } else if (command === 'performance') {
    ElMessage.info('绩效统计功能开发中')
  } else if (command === 'disable') {
    const newStatus = department.status === '正常运营' ? '暂停服务' : '正常运营'
    try {
      await departmentStore.updateDepartment(department.id, { status: newStatus })
      ElMessage.success(`${newStatus === '正常运营' ? '恢复' : '暂停'}服务成功`)
    } catch (error) {
      ElMessage.error('操作失败')
    }
  } else if (command === 'delete') {
    try {
      await ElMessageBox.confirm(
        `确定要删除科室"${department.name}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      await departmentStore.deleteDepartment(department.id)
      ElMessage.success('删除成功')
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '删除失败')
      }
    }
  }
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    if (editingDepartment.value) {
      await departmentStore.updateDepartment(editingDepartment.value.id, departmentForm.value)
      ElMessage.success('更新成功')
    } else {
      await departmentStore.addDepartment(departmentForm.value)
      ElMessage.success('添加成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    console.error('保存失败:', error)
  }
}

const resetForm = () => {
  editingDepartment.value = null
  formRef.value?.resetFields()
  Object.assign(departmentForm.value, {
    name: '',
    code: '',
    type: '',
    level: '',
    parentId: '',
    parentName: '',
    director: {
      id: '',
      name: '',
      title: '',
      phone: '',
      email: ''
    },
    viceDirectors: [],
    location: {
      building: '',
      floor: '',
      room: '',
      description: ''
    },
    contact: {
      phone: '',
      extension: '',
      email: '',
      fax: ''
    },
    capacity: {
      beds: 0,
      doctors: 0,
      nurses: 0,
      currentPatients: 0
    },
    services: [],
    equipment: [],
    workingHours: {
      weekdays: {
        start: '08:00',
        end: '17:30'
      },
      weekends: {
        start: '08:00',
        end: '12:00'
      },
      holidays: false
    },
    budget: {
      annual: 0,
      used: 0,
      remaining: 0,
      categories: []
    },
    performance: {
      monthlyVisits: 0,
      satisfaction: 5,
      revenue: 0,
      costs: 0,
      profit: 0
    },
    status: '正常运营',
    description: '',
    foundedDate: new Date().toISOString().split('T')[0]
  })
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

const exportData = () => {
  ElMessage.info('导出功能开发中')
}

// 样式辅助方法
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    '临床科室': 'primary',
    '医技科室': 'success',
    '行政科室': 'warning',
    '后勤科室': 'info'
  }
  return colorMap[type] || 'info'
}

const getLevelColor = (level: string) => {
  const colorMap: Record<string, string> = {
    '一级科室': 'danger',
    '二级科室': 'warning',
    '三级科室': 'success'
  }
  return colorMap[level] || 'info'
}

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '正常运营': 'success',
    '暂停服务': 'warning',
    '科室调整': 'info',
    '筹建中': 'primary'
  }
  return colorMap[status] || 'info'
}

const getEquipmentStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '正常': 'success',
    '维修': 'warning',
    '停用': 'danger'
  }
  return colorMap[status] || 'info'
}

onMounted(() => {
  departmentStore.getDepartments()
})
</script>

<style lang="scss" scoped>
.department-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.stats-cards {
  margin-bottom: 20px;

  .stat-card {
    .stat-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 24px;
      }

      .stat-info {
        .stat-value {
          font-size: 24px;
          font-weight: 700;
          color: #303133;
          line-height: 1;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-top: 4px;
        }
      }
    }
  }
}

.search-card {
  margin-bottom: 20px;

  .stats-info {
    display: flex;
    align-items: center;
    gap: 20px;

    .stat-item {
      font-size: 14px;
      color: #666;

      strong {
        color: #409EFF;
        margin-left: 4px;
      }
    }
  }
}

.department-tree {
  .tree-node {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: 1;
    padding: 8px 12px;
    border-radius: 4px;

    &:hover {
      background: #f5f7fa;
    }

    .node-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .node-name {
        font-weight: 600;
        color: #303133;
      }

      .node-stats {
        font-size: 12px;
        color: #909399;
      }
    }

    .node-actions {
      display: flex;
      gap: 8px;
    }
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.department-detail {
  .service-tag {
    margin-right: 8px;
    margin-bottom: 4px;
  }

  .capacity-card {
    h4 {
      margin: 0 0 16px 0;
      color: #303133;
    }

    .capacity-info {
      .capacity-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;

        span {
          color: #606266;
        }

        strong {
          color: #303133;
        }
      }
    }
  }

  .satisfaction-section {
    text-align: center;

    h4 {
      margin-bottom: 16px;
    }
  }
}

.form-content {
  max-height: 500px;
  overflow-y: auto;
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .stats-cards {
    :deep(.el-col) {
      margin-bottom: 16px;
    }
  }

  .search-card {
    :deep(.el-row) {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }

  .tree-node {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 8px;

    .node-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }
}
</style>